import { PageConfig } from 'next';
import an48 from '@mmstudio/an000048';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import { sign } from 'jsonwebtoken';
import mmconf from '@mmstudio/config';
import an47 from '@mmstudio/an000047';
import a002 from '../../../atoms/md5';
import getkey from '../../../atoms/key';
import { tbfdrole, tbfduser } from '../../../atoms/db';

const logger = anylogger('pages/api/account/login.api');

const session = mmconf.session as {
	secret: string;
	expiresIn: string | number;
};

export type Result = false | string;

export type Message = {
	account: string;
	password: string;
}

/**
 * 登陆服务
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { account, password } = req.body as Message;
		const md5 = a002(password);
		const user = await tbfduser().first('*').where({
			userid: account,
			psw: md5
		});
		if (!user) {
			const msg = '账号或密码错误';
			res.statusMessage = encodeURIComponent(msg);
			res.status(500).end(msg);
			return;
		}

		const role = await tbfdrole()
			.first<{
				name: string;
				userid: string;
			}>({
				name: 'fdrole.name',
				userid: 'fduserrole.userid'
			})
			.rightJoin('fduserrole', 'fduserrole.roleid', 'fdrole.roleid')
			.where({
				userid: user.userid
			});

		const { psw: m, ...rest } = user;	// remove password

		const token = sign({
			...rest,
			role: role?.name
		}, session.secret, { expiresIn: session.expiresIn, algorithm: 'HS256' });
		logger.debug('userlogin success', user, 'token', token);
		(() => {
			const key = getkey();
			return an47(res, key, token, { sameSite: 'lax', httpOnly: true });
		})();
		res.status(200).json(JSON.stringify(token));
	} catch (error) {
		logger.error(error);
		const msg = (error as Error).message;
		res.statusMessage = encodeURIComponent(msg);
		res.status(500).end(msg);
	}
});

export const config = {} as PageConfig;

export default handler;
